package com.seafwg.web;

import com.seafwg.service.UserService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author seafwg
 * @Date 2022/2/15 10:40 上午
 * @Version 1.0
 * @description 通过spring集成web环境，利用spring提供的监听器中添加的应用实例
 * 通过spring提供的WebApplicationContextUtils(ServletContext servletContext)传递servletContext，servlet上下文创建实例
 */

public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取servlet上下文
        ServletContext servletContext = req.getServletContext();
        // WebApplicationContextUtils静态方法获取应用实例
        WebApplicationContext webapp = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService = webapp.getBean(UserService.class);
        System.out.println("UserServlet in exe...");
        userService.save();
        System.out.println("UserServlet out exe...");
    }
}
